package com.zhz.lib.cms.manage.newscenter.action;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import com.zhz.lib.cms.domain.newscenter.News;
import com.zhz.lib.cms.domain.type.Sortmap;
import com.zhz.lib.cms.manage.BaseActionWithApprove;
import com.zhz.lib.cms.utils.zhz.ZhzSecurityUtil;
import com.zhz.lib.cms.utils.zhz.ZhzSortMapUtil;
import com.zhz.lib.cms.vo.newscenter.NewsVO;
import com.zhz.project.common.util.alibaba.StringUtil;
import com.zhz.project.common.util.hibernate.BaseDAO;
import com.zhz.project.common.util.zhzutil.ZhzDateUtil;
import com.zhz.project.common.util.zhzutil.ZhzHttpRequestUtil;
import com.zhz.project.common.util.zhzutil.ZhzStringUtil;

public class NewsAction extends BaseActionWithApprove {

    private static final int    length = 30;
    private static String       TABLE  = "News";
    private static String       KEY    = "newsId";
    private static String       LIST   = "newslist";

    private static Logger       logger = Logger.getLogger(NewsAction.class);

    // 最新消息来源系列downlist ID
    private Integer             newsfromfatherid;
    // 最新消息类别系列的 downlist ID
    private Integer             newstypefatherid;
    // 事务模板
    private TransactionTemplate transactionTemplate;

    // 不给参数，默认执行此处
    @Override
    public ActionForward unspecified(ActionMapping mapping, ActionForm form,
                                     HttpServletRequest request, HttpServletResponse response)
                                                                                              throws Exception {
        return newslist(mapping, form, request, response);
    }

    /**
     * 显示最新消息列表
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public ActionForward newslist(ActionMapping mapping, ActionForm form,
                                  HttpServletRequest request, HttpServletResponse response)
                                                                                           throws Exception {

        // ////////////////////////////////////////////////////////////////////////
        // 取出选择的馆内馆内信息类型
        String radiooption = ZhzHttpRequestUtil.getParameters(request, "radiooption");

        // 获取新闻来源
        String newsfrom = ZhzHttpRequestUtil.getParameters(request, "newsfrom");
        // 获取新闻类型
        String sortType = ZhzHttpRequestUtil.getParameters(request, "sortType");

        request.setAttribute("radiooption", radiooption);
        request.setAttribute("newsfrom", newsfrom);
        request.setAttribute("sortType", sortType);

        // 上面是提取参数并输出到页面中
        // ////////////////////////////////////////////////////////////////////////

        String whereStatement = BaseDAO.WHERE;
        StringBuffer fanyeHref = new StringBuffer();
        fanyeHref.append("newsManage.do?method=newslist");

        // 根据选择的链接类型选项进行查询
        if (StringUtil.isNotBlank(radiooption)) {
            if (StringUtil.equals(radiooption, "zhiding")) {
                whereStatement += " and  top=" + 1;
            }
            fanyeHref.append("&radiooption=");
            fanyeHref.append(radiooption);
        }

        // 根据新闻来源进行查询
        if (StringUtil.isNotBlank(sortType)) {
            whereStatement += "and sortType =" + sortType;
            fanyeHref.append("&sortType=");
            fanyeHref.append(sortType);
        }
        // 根据新闻类型进行查询
        if (StringUtil.isNotBlank(newsfrom)) {
            whereStatement += " and newsfrom =" + newsfrom;
            fanyeHref.append("&newsfrom=");
            fanyeHref.append(newsfrom);
        }

        List<News> newslist = getListWithFanyeHref(request, TABLE, whereStatement
                                                                   + BaseDAO.WHERE_DELETE,
            " order by " + KEY + " DESC", LIST, fanyeHref);

        List<NewsVO> newsVOlist = new ArrayList<NewsVO>();
        if (newslist != null && newslist.size() > 0) {
            for (News news : newslist) {
                newsVOlist.add(changeToVo(news, true));
            }
        }

        // 查询的结果集
        request.setAttribute(LIST, newsVOlist);

        return mapping.findForward("news-list");
    }

    /**
     * 添加最新消息
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    public ActionForward newsadd(ActionMapping mapping, ActionForm form,
                                 HttpServletRequest request, HttpServletResponse response) {

        request.setAttribute("writer", ZhzSecurityUtil.getOperatorName());

        // 列出最新消息来源
        request.setAttribute("newsfrominfolist", ZhzSortMapUtil.getChildSortMapList(
            newsfromfatherid, baseDao));
        // 列出最新消息类型
        request.setAttribute("newstypeinfolist", ZhzSortMapUtil.getChildSortMapList(
            newstypefatherid, baseDao));

        return mapping.findForward("news-add");

    }

    /**
     * 提交最新消息
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    public ActionForward newssave(ActionMapping mapping, ActionForm form,
                                  HttpServletRequest request, HttpServletResponse response) {
        // 获取最新消息的标题
        String title = ZhzHttpRequestUtil.getParameters(request, "title");
        // 获取最新消息的主内容
        String newscontent = ZhzHttpRequestUtil.getParameters(request, "newscontent");
        // 获取最新消息的来源
        String newsfrom = ZhzHttpRequestUtil.getParameters(request, "newsfrom");
        // 获取最新消息的类型
        String newstype = ZhzHttpRequestUtil.getParameters(request, "newstype");

        News news = new News();

        news.setTitle(title);
        news.setContent(newscontent);
        news.setWriter(ZhzSecurityUtil.getOperatorName());
        news.setKeyword(null);
        news.setNewsfrom(newsfrom);
        news.setSortType(newstype);
        String pubdate = request.getParameter("pubdate");
        if (StringUtil.isNotBlank(pubdate)) {
            news.setPubDate(ZhzDateUtil.getYYYYMDDDate(request.getParameter("pubdate")));
        } else {
            news.setPubDate(new Date());
        }
        if (ZhzStringUtil.isNotNull(request.getParameter("iftop"))) {
            news.setTop(1);
            news.setTopStartTime(ZhzDateUtil.getYYYYMDDDate(request.getParameter("startdate")));
            news.setTopEndTime(ZhzDateUtil.getYYYYMDDDate(request.getParameter("enddate")));
        } else {
            news.setTop(0);
            news.setTopStartTime(null);
            news.setTopEndTime(null);
        }
        news.setHit(0);
        news.setAproveState(0);
        news.setAproveTime(null);
        news.setEditor(ZhzSecurityUtil.getOperatorName());
        news.setEditorTime(new Date());
        news.setIfDelete(0);

        request.setAttribute("add", true);

        boolean x = baseDao.save(news);

        if (x) {
            request.setAttribute("add", "add");
            request.setAttribute("addresult", "addresult");
        }

        return mapping.findForward("news-result");
    }

    /**
     * 编辑最新消息
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    public ActionForward newsedit(ActionMapping mapping, ActionForm form,
                                  HttpServletRequest request, HttpServletResponse response) {
        String newsid = ZhzHttpRequestUtil.getParameters(request, "newsid");
        // 获取信息最新消息
        News news = (News) baseDao.findOneObject("News", "newsId", newsid);
        request.setAttribute("news", news);

        Sortmap newsfrom = (Sortmap) baseDao.findOneObject("Sortmap", "sortMapId", news
            .getNewsfrom());
        request.setAttribute("newsfrom", newsfrom);

        Sortmap sortType = (Sortmap) baseDao.findOneObject("Sortmap", "sortMapId", news
            .getSortType());
        request.setAttribute("sortType", sortType);

        if (news.getTop() == 1)
            request.setAttribute("top", true);
        else
            request.setAttribute("top", false);

        // 列出最新消息来源
        request.setAttribute("newsfrominfolist", ZhzSortMapUtil.getChildSortMapList(
            newsfromfatherid, baseDao));
        // 列出最新消息类型
        request.setAttribute("newstypeinfolist", ZhzSortMapUtil.getChildSortMapList(
            newstypefatherid, baseDao));

        return mapping.findForward("newsedit-form");
    }

    /**
     * 编辑最新消息提交
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    public ActionForward newseditsave(ActionMapping mapping, ActionForm form,
                                      HttpServletRequest request, HttpServletResponse response) {

        String newsid = ZhzHttpRequestUtil.getParameters(request, "newsid");

        // 获取最新消息的标题
        String title = ZhzHttpRequestUtil.getParameters(request, "title");
        // 获取最新消息的主内容
        String newscontent = ZhzHttpRequestUtil.getParameters(request, "newscontent");
        // 获取最新消息的来源
        String newsfrom = ZhzHttpRequestUtil.getParameters(request, "newsfrom");
        // 获取最新消息的类型
        String newstype = ZhzHttpRequestUtil.getParameters(request, "newstype");

        News news = (News) baseDao.findOneObject("News", "newsId", newsid);

        news.setTitle(title);
        news.setContent(newscontent);
        news.setNewsfrom(newsfrom);
        news.setSortType(newstype);
        String pubdate = request.getParameter("pubdate");
        if (StringUtil.isNotBlank(pubdate)) {
            news.setPubDate(ZhzDateUtil.getYYYYMDDDate(request.getParameter("pubdate")));
        } else {
            news.setPubDate(new Date());
        }
        if (ZhzStringUtil.isNotNull(request.getParameter("iftop"))) {
            news.setTop(1);
            news.setTopStartTime(ZhzDateUtil.getYYYYMDDDate(request.getParameter("startdate")));
            news.setTopEndTime(ZhzDateUtil.getYYYYMDDDate(request.getParameter("enddate")));
        } else {
            news.setTop(0);
            news.setTopStartTime(null);
            news.setTopEndTime(null);
        }
        news.setEditor(ZhzSecurityUtil.getOperatorName());
        news.setEditorTime(new Date());

        request.setAttribute("edit", true);
        boolean x = baseDao.update(news);

        if (x) {
            request.setAttribute("edit", "edit");
            request.setAttribute("editresult", "editresult");
        }

        return mapping.findForward("news-result");
    }

    /**
     * 删除最新消息
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward newsdel(ActionMapping mapping, ActionForm form,
                                 HttpServletRequest request, HttpServletResponse response)
                                                                                          throws Exception {
        boolean delResult = false;

        String newsidString = ZhzHttpRequestUtil.getParameters(request, "newsid");

        if (ZhzStringUtil.isNotNull(newsidString)) {
            News news = (News) baseDao.findOneObject("News", "newsId", newsidString);
            // 设为删除
            news.setIfDelete(1);
            news.setEditor(ZhzSecurityUtil.getOperatorName());
            news.setEditorTime(new Date());

            delResult = baseDao.update(news);
        }
        if (delResult) {
            request.setAttribute("del", "del");
            request.setAttribute("delResult", "delResult");
        }
        return mapping.findForward("news-result");
    }

    /**
     * 通过ajax请求，获取最新消息列表
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward newsContent(ActionMapping mapping, ActionForm form,
                                     HttpServletRequest request, HttpServletResponse response)
                                                                                              throws Exception {
        String newsid = ZhzHttpRequestUtil.getParameters(request, "newsid");
        if (ZhzStringUtil.isNotNull(newsid)) {
            News news = (News) baseDao.findOneObject("News", "newsId", newsid);
            request.setAttribute("news", changeToVo(news, false));
        } else {
            return null;
        }
        return mapping.findForward("news-content");
    }

    /**
     * 审核最新消息
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public ActionForward newsApprove(ActionMapping mapping, ActionForm form,
                                     HttpServletRequest request, HttpServletResponse response)
                                                                                              throws Exception {
        // 获取所有的参数
        Enumeration allParameter = request.getParameterNames();

        // 0 未审核 1 通过 2 不通过
        String aproveState = ZhzStringUtil.ISOtoUTF8AfterTrimIfNotNull(request
            .getParameter("approveState"));

        final int apoveStateInt = Integer.parseInt(aproveState);

        // 获取选择的所有待审核的模块
        final Set<String> newsIdSet = new HashSet<String>();

        String name = null;
        while (allParameter.hasMoreElements()) {
            name = (String) allParameter.nextElement();
            if (ZhzStringUtil.isNotNull(name) && StringUtil.contains(name, "checkbox")) {
                // 将含有值的checkbox，赋值
                newsIdSet.add(request.getParameter(name));
            }
        }

        // 在事务中进行
        boolean approveResult = (Boolean) transactionTemplate.execute(new TransactionCallback() {

            public Object doInTransaction(TransactionStatus status) {

                try {
                    Iterator it = newsIdSet.iterator();
                    while (it.hasNext()) {
                        String newsId = (String) it.next();
                        News news = (News) baseDao.findOneObject("News", "newsId", newsId);
                        news.setAproveState(apoveStateInt);
                        news.setAproveTime(Calendar.getInstance().getTime());
                        news.setEditor(ZhzSecurityUtil.getOperatorName());
                        news.setEditorTime(new Date());

                        baseDao.update(news);
                    }
                } catch (Exception e) {
                    status.setRollbackOnly();
                    return false;
                }
                return true;
            }
        });

        if (approveResult) {
            request.setAttribute("app", "app");
            request.setAttribute("approveResult", "approveResult");
        }
        return mapping.findForward("news-result");
    }

    /**
     * 将news转换为页面需要的数据
     * 
     * @param news
     * @throws Exception 
     */
    private NewsVO changeToVo(News news, boolean needCut) throws Exception {
        NewsVO newsVO = new NewsVO();
        BeanUtils.copyProperties(news, newsVO);
        Sortmap smp = (Sortmap) baseDao.findOneObject("Sortmap", "sortMapId", news.getNewsfrom());
        if (smp != null)
            newsVO.setNewsfromString(smp.getValue());
        smp = (Sortmap) baseDao.findOneObject("Sortmap", "sortMapId", news.getSortType());
        if (smp != null)
            newsVO.setSortTypeString(smp.getValue());

        if (needCut && StringUtil.isNotBlank(newsVO.getTitle()))
            if (newsVO.getTitle().getBytes().length > length)
                newsVO.setTitle(ZhzStringUtil.subStringWithDot(newsVO.getTitle(), length));
        return newsVO;
    }

    public void setNewstypefatherid(Integer newstypefatherid) {
        this.newstypefatherid = newstypefatherid;
    }

    public void setNewsfromfatherid(Integer newsfromfatherid) {
        this.newsfromfatherid = newsfromfatherid;
    }

    @Override
    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }

}